package handler;

import bean.User;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Register implements Controller {
    private UserService service;

    public void setService(UserService service) {
        this.service = service;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        ModelAndView modelAndView = new ModelAndView("register");
        if (req.getMethod().equals("POST")) {
            String userName = req.getParameter("user-name");
            String password = req.getParameter("password");
            if (!User.verifyUserName(userName)) {
                modelAndView.addObject("error", "用户名的长度不符合规范");
                return modelAndView;
            }
            if (!User.verifyPassword(password)) {
                modelAndView.addObject("error", "密码的长度不符合规范");
                return modelAndView;
            }
            // 如果数据库表中已存在指定用户名
            if (service.verify(userName)) {
                modelAndView.addObject("error", "注册失败，用户名可能已存在");
            } else {
                User user = new User(userName, password);
                if (service.register(user)) {
                    modelAndView.setViewName("redirect:login");
                } else {
                    modelAndView.addObject("error", "注册失败，未知错误");
                }
            }
        }
        return modelAndView;
    }
}
